//
//  SwiftyJSONAble.swift
//  ifanr
//
//  Created by zwb on 16/9/3.
//  Copyright © 2025 aowang. All rights reserved.
//

import Foundation
import Moya

public protocol SwiftyJSONAble {
    init(json: JSON)
}

public extension Response {

    /// Maps data received from the signal into an object which implements the SwiftyJSONAble protocol.
    /// If the conversion fails, the signal errors.
    func mapObject<T: SwiftyJSONAble>(_ type: T.Type) throws -> T {
        let jsonObject = try mapJSON()

//        guard let mappedObject = T(json: JSON(jsonObject)) else {
//            throw Error.JSONMapping(self)
//        }

        return T(json: JSON(jsonObject))
    }

    /// Maps data received from the signal into an array of objects which implement the SwiftyJSONAble protocol
    /// If the conversion fails, the signal errors.
    func mapArray<T: SwiftyJSONAble>(_ type: T.Type) throws -> [T] {
        let jsonObject = try mapJSON()

        let mappedArray = JSON(jsonObject)
        let mappedObjectsArray = mappedArray.arrayValue.compactMap { T(json: $0) }

        return mappedObjectsArray
    }
}
